import { getRegion } from "@/api/modules/user";
import { Cascader } from "antd";
import { useEffect, useState } from "react";
import { map } from "lodash";

interface Props {
	[key: string]: any;
	disabled: boolean;
}

export default (props: Props) => {
	const { provinceOptions = [] } = props;
	const [options, setOptions] = useState<any[]>(provinceOptions);
	const [value, setValue] = useState<string[]>([]);

	useEffect(() => {
		if (props.value) setValue([props?.value?.province, props?.value?.city, props?.value?.county]);
	}, [props?.value]);

	useEffect(() => {
		if (!provinceOptions.length)
			getRegion({ pid: 0 }).then(res => {
				setOptions(
					map(res?.data, i => ({
						...i,
						isLeaf: false
					}))
				);
			});
	}, []);

	const onChange = (value: string[], selectedOptions: any[]) => {
		// console.log("=======", value, selectedOptions);
		setValue(value);
		if (value?.length === 3) {
			props.onChange?.({
				province: value?.[0],
				city: value?.[1],
				county: value?.[2]
			});
		}
	};

	const loadData = (selectedOptions: any[]) => {
		const targetOption = selectedOptions[selectedOptions.length - 1];
		targetOption.loading = true;

		getRegion({ pid: targetOption?.id }).then(res => {
			targetOption.loading = false;

			targetOption.children = map(res?.data, i => ({
				...i,
				isLeaf: i?.level === 2
			}));
			setOptions([...options]);
		});
	};

	return (
		<Cascader
			value={value}
			placeholder="请选择省市区"
			fieldNames={{ label: "name", value: "name", children: "children" }}
			options={options}
			loadData={loadData}
			onChange={onChange}
			changeOnSelect={true}
			disabled={props.disabled}
		/>
	);
};
